/**
 * @description 订单数据操作
 * @author liyunfu
 */

const Order = require("../../models/Order");
const Address = require("../../models/Address");
const Product = require("../../models/Product");
!(async () => {
  //创建订单
  const requestBody = {
    addressId: "61d0fcdd33b11f03c784e61a",
    shopId: "61da2b298ebd89a847161ab5",
    shopName: "沃尔玛",
    isCanceled: false, //订单是否被取消
    products: [
      {
        id: "61da2dcff2981622a78dbccf",
        num: 3, //购买数量
      },
      {
        id: "61da2dd0f2981622a78dbcd2",
        num: 5, //购买数量
      },
    ],
  };

  //获取address
  const address = await Address.findById(requestBody.addressId);

  //获取商品列表
  const pIds = requestBody.products.map((p) => p.id); //[xxx,xxx]
  const productList = await Product.find({
    shopId: requestBody.shopId, //沃尔玛的商品
    _id: {
      $in: pIds,
    },
  });
  //整合订单购买数量
  const productListWithSales = productList.map((p) => {
    //商品id
    const id = p._id.toString();
    //找到商品的购买数量
    const filterProducts = requestBody.products.filter(
      (item) => item.id === id
    );
    if (filterProducts.length === 0) {
      throw Error("未找到匹配的数据");
    }

    return {
      product: p,
      oderSales: filterProducts[0].num,
    };
  });

  await Order.create({
    username: "zhangsan",
    shopId: requestBody.shopId,
    shopName: requestBody.shopName,
    isCanceled: requestBody.isCanceled,
    address,
    product: productListWithSales,
  });
})();
